from socketio import Namespace
from jwt import decode
from django.conf import settings
from urllib.parse import parse_qs
from socketio.exceptions import ConnectionRefusedError
from redis import Redis


class BaseNamespace(Namespace):

    def on_connect(self, sid, env):
        query = env["QUERY_STRING"]
        query = parse_qs(query)
        try:
            print(query)
            payload = decode(query['Access-Token'][0], key=settings.SECRET_KEY)
        except Exception as e:
            raise ConnectionRefusedError('authentication failed')
        else:
            with self.session(sid) as sess:
                red: Redis = Redis.from_url(settings.SOCKET_SID_SAVE_REDIS_URL)
                red.set(f'{payload["username"]}-{sid}', sid, ex=60 * 60 * 12 * 7)
                sess['user'] = payload['id']
                sess['key'] = f'{payload["username"]}-{sid}'
            self.enter_room(sid,payload["username"])

    def on_disconnect(self, sid):
        with self.session(sid) as sess:
            red: Redis = Redis.from_url(settings.SOCKET_SID_SAVE_REDIS_URL)
            key:str = sess['key']
            red.delete(key)


    def on_test(self,sid,data):
        print(data,'===============')
        print(data,'===============')
        print(data,'===============')
        print(data,'===============')
        print(data,'===============')
        print(data,'===============')
        print(data,'===============')
        print(data,'===============')
        print(data,'===============')
        print(data,'===============')
